package com.dingpeikeji.quickdeer.modules.base.web;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.beanvalidator.BeanValidators;
import com.dingpeikeji.quickdeer.core.common.mapper.JsonMapper;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.utils.MD5Utils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.modules.applycargo.entity.TApplycargo;
import com.dingpeikeji.quickdeer.modules.applycargo.service.TApplycargoService;
import com.dingpeikeji.quickdeer.modules.base.entity.QqParam;
import com.dingpeikeji.quickdeer.modules.realsche.service.FRealscheService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProRentOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentgroup;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.modules.sms.entity.Sms;
import com.dingpeikeji.quickdeer.modules.sms.service.CkeckTelephoneService;
import com.dingpeikeji.quickdeer.modules.sms.service.SmsApi;
import com.dingpeikeji.quickdeer.modules.utils.ValidateCodeTool;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.utils.JedisClient;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import net.sf.json.JSONObject;
 

@Controller
@RequestMapping("/f/sms")
public class FSmsController extends BaseController{
	// 验证码用途
	public static final String[] validateCodeTypes = new String[]{"validateCodeFromPhoneForRegister","validateCodeFromPhoneForDriver", "validateCodeFromPhoneForPassword"};
	@Autowired
	private CkeckTelephoneService ckeckTelephoneService;
	@Autowired
	private TApplycargoService tApplycargoService;
	@Autowired
	private FRealscheService fRealscheService;
	@Autowired
	private JedisClient jedisClient;
	@Autowired
	private TRentproductService tRentproductService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private TCargotypeService tCargotypeService;
	@Autowired
	private TRentgroupService tRentgroupService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@RequestMapping("send")
	@ResponseBody
	public String send(String phone, Integer type, HttpServletRequest request) {
		if(ValidateTool.isEmptyOrNull(phone) || !ValidateTool.isMobile(phone)) {
			return "手机号非法,请重新输入";
		}
		if(type == null || type<0 || type > 2){
			//return "未知用途";
			return "发送短信出错,请联系网站管理员";
		}
		String sessionValue = validateCodeTypes[type]; // 验证码session值
		@SuppressWarnings("unchecked")
		Map<String,Object> map = (Map<String,Object>)request.getSession().getAttribute(sessionValue);
		if(map != null) {
			Long time = (Long) map.get("time"); // 时间毫秒数
			Date date = new Date();
			Long wait = 60*1000L*2; // 验证码等待毫秒数
			if(time+wait >= date.getTime()) {
				return "验证码已发送，请耐心等待";
			}
		}
		// 开始发送短信
		String code = ValidateCodeTool.genCode();
		System.out.println("手机验证码"+code);
		try {
			Sms sendSms = new Sms();
			sendSms.setMobile(phone);
			sendSms.setContent("本次验证码为："+code+"，有效时间为2分钟");
			if (SmsApi.sendSms(sendSms) == false)
				return "发送失败";
		} catch (Exception e) {
			return "系统异常";
		}
		map = Maps.newHashMap();
		map.put("time", new Date().getTime());
		map.put("code", code);
		jedisClient.set("registercode: "+phone, code);
		//重置token的过期时间
		jedisClient.expire("registercode: "+phone, 60*2);
		request.getSession().setAttribute(sessionValue, map);
		return "success";
	}
	
	@RequestMapping("checkTel")
	public void checkTel(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String tel = request.getParameter("mobile");
		if(ValidateTool.isEmptyOrNull(tel) || !ValidateTool.isMobile(tel)) {
			response.getWriter().println("2");
			return;
		}
		User user = ckeckTelephoneService.getUserByTelephone(tel);
		if (user == null) {  //手机号未注册,可以使用
			response.getWriter().println("1");
		} else {
			response.getWriter().println("0");
		}
	}
	@RequestMapping("checkTime")
	public void checkTime(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException {
		String time = request.getParameter("time");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date userTime = sdf.parse(time);
		Long fromdateLong = userTime.getTime() - 60*60*1000*2;
		if(new Date(fromdateLong).before(new Date())){
			//return "距离发车时间不足2小时，请重新选择发车时间";
			response.getWriter().println("1");
		} else{
			response.getWriter().println("0");
		}
	}
	@RequestMapping("checkBackTime")
	public void checkBackTime(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException {
		String orderid = request.getParameter("orderid");
		TOrders torders = fRealscheService.getOrders(orderid);
		if (torders.getDepartdate().before( new Date())) {
			response.getWriter().println("1");//已过发车时间
		}else{
			response.getWriter().println("0");
		}
	}
	@RequestMapping("getSiteId")
	public void getSiteId(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String sitename = request.getParameter("sitename");
		String siteid = tSitedtlService.getSiteIdByName(sitename);
		response.getWriter().println(siteid);
	}
	@RequestMapping("checkSiteid")
	public void checkSiteid(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String siteid = request.getParameter("siteid");
		if (siteid==null||"".equals(siteid)||"null".equals(siteid)||"null\n".equals(siteid)) {
			response.getWriter().println(1);//不支持此地区
		}else{
			response.getWriter().println(0);
		}
	}
	@RequestMapping("details")
	public String details(TRentproduct tRentproduct, Model model, HttpServletRequest request
			,HttpServletResponse response) throws Exception {
		String viewPage = "modules/rentproduct/fRentproductFor{0}Details"; // 视图
		// 根据ID查询选中的整车信息
		TRentproduct rentproduct = tRentproductService.get(tRentproduct.getRentid());
		TRentgroup rentgroup = tRentgroupService.get(rentproduct.getRentgrpid());
		if (rentproduct != null) {

			// 协议价逻辑处理
			TRentproduct query = new TRentproduct();
			query.setRentid(tRentproduct.getRentid());
			query.setDepartdate(DateUtils.parseDate(tRentproduct.getFromdateStr() + " " + tRentproduct.getTime()));

			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request, "f");
			query = rentproductService.getSuitrtnprice(query);
				rentproduct.setSuitrtnprice(query.getSuitrtnprice());
		}

		// 数据校验

		// 消息集合
		List<String> messages = Lists.newArrayList();

		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);

		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if (warningFor2Hours != null) {
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}

		// 当前下午2点停止卖票
		if (messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if (warningFor14Hours != null) {
				messages.add(warningFor14Hours);
			}
		}
		if (!messages.isEmpty()) {
			addMessage(model, messages.toArray(new String[] {}));
		}
		model.addAttribute("tRentproduct", rentproduct);
		model.addAttribute("rentgroup", rentgroup);
		model.addAttribute("query", tRentproduct);
		String format = MessageFormat.format(viewPage, rentproductService.getRentTypeName(tRentproduct.getRentType()));
		return format;
	}
	@RequestMapping("airdetails")
	public String airDetails(TRentproduct tRentproduct, Model model, HttpServletRequest request
			,HttpServletResponse response) throws Exception {
		//根据车队abbr和name查询车队id
		String id = officeService.findIdByNameAndAbbr(tRentproduct.getOffice().getName(),tRentproduct.getOffice().getAbbr());
		tRentproduct.getOffice().setId(id);
		model.addAttribute("tRentproduct", tRentproduct);
		return "modules/rentproduct/fRentproductForAirplaneDetails";
	}
	@RequestMapping("booking")
	public String booking(TOrders orders, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request,HttpServletResponse response) throws Exception {
		//String redirctPage = "redirect:/f/rentproduct/details?repage&time={0}&daysnum={1}&rentid={2}&rentType={3}&fromdateStr={4}"; // 订单信息页
		String redirctPage = "redirect:/f/rentproduct/details?time={0}&daysnum={1}&rentid={2}&rentType={3}&fromdateStr={4}"; // 订单信息页
		String payWayPage = "redirect:/f/pay/payWay?orderid={0}"; // 支付方式选择页
		User user = (User) request.getSession().getAttribute(FSysController.FRONT_USER_IN_SESSION);
		orders.setOrderuserid(user.getId());
		//行程备注
		/*Map<Integer, String> map = new HashMap<Integer, String>();
		String[] arr = orders.getRemarks().split(",");
		for (int i = 0; i < arr.length+1/2; i+=2) {//[常州, 无锡, 无锡, 宿州]0-1 2-3
			map.put(i/2+1,arr[i]+"--"+arr[i+1] );
		}
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<Integer, String> en : map.entrySet()) {
			sb.append("第"+en.getKey()+"天:"+en.getValue()+"\r\n");
		}
		orders.setRemarks(sb.toString());*/
		// 校验数据

		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息

		TRentproduct tRentproduct = new TRentproduct();
		tRentproduct.setFromdateStr(orders.getFromdateStr());
		tRentproduct.setTime(orders.getTime());
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);

		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if (warningFor2Hours != null) {
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}

		// 当前下午2点停止卖票
		if (messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if (warningFor14Hours != null) {
				messages.add(warningFor14Hours);
			}
		}

		if (messages.isEmpty()) {
			// 协议价逻辑处理

			TRentproduct query = new TRentproduct();
			query.setRentid(Integer.parseInt(orders.getRealscheid()));
			query.setDepartdate(DateUtils.parseDate(orders.getDepartdateStr()));

			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request, "f");
			query = rentproductService.getSuitrtnprice(query);
			Double suitrtnprice = query.getSuitrtnprice();
			if (orders.getBookingdays()==0) {
				suitrtnprice = Math.rint(suitrtnprice * 0.8);//四舍五入取整
			}
			orders.setDueamount("" + suitrtnprice);
			Integer purchasenum = Integer.valueOf(orders.getPurchasenum());
			if (orders.getOrdertype().equals(TOrders.ORDER_TYPE_RENTPRODUCT_DAY)) {
				if (orders.getBookingdays()==0) {
					orders.setDueamount("" + Math.rint(query.getSuitrtnprice()*0.8 * 1 * purchasenum));
				}else{
					orders.setDueamount("" + query.getSuitrtnprice() * orders.getBookingdays() * purchasenum);
				}
			} else {
				orders.setDueamount("" + query.getSuitrtnprice() * purchasenum);
			}

			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				boolean success = pro.success();
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					String format = MessageFormat.format(payWayPage, orderid.toString());
					return format;//redirect:/f/pay/payWay?orderid=11000777
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		redirectAttributes.addFlashAttribute("orders", orders);
		addMessage(redirectAttributes, messages.toArray(new String[] {}));
		String format = MessageFormat.format(redirctPage, orders.getTime(), orders.getBookingdays().toString(),
				orders.getRealscheid().toString(), orders.getOrdertype(), orders.getFromdateStr());
		return format;
	}
	@RequestMapping("airbooking")
	public String airbooking(TOrders orders, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request,HttpServletResponse response,TRentproduct tRentproduct) throws Exception {
		//String redirctPage = "redirect:/f/rentproduct/details?time={0}&daysnum={1}&rentid={2}&rentType={3}&fromdateStr={4}"; // 订单信息页
		//接收出发地,目的地
		String departcitySitename = request.getParameter("departcity.sitename");
		String destcitySitename = request.getParameter("destcity.sitename");
		orders.setDepartcity(departcitySitename);
		orders.setDestcity(destcitySitename);
		orders.setBookingdays(1);//接送机默认一天
		orders.setCargotypeid(tRentproduct.getCargotype().getCargotypeid());
		//orders.getOffice().setId(id);
		//orders.setOfficeids(tRentproduct.getOffice().getId());
		String payWayPage = "redirect:/f/pay/payWay?orderid={0}"; // 支付方式选择页
		User user = (User) request.getSession().getAttribute(FSysController.FRONT_USER_IN_SESSION);
		orders.setOrderuserid(user.getId());
		//设置realscheid,
		orders.setRealscheid(System.currentTimeMillis()/1000+"");
		//设置价格
		orders.setDueamount(request.getParameter("totalPrice"));
		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);
		//处理时间
		orders.setDepartdateStr(orders.getFromdateStr()+ " " + orders.getTime());
		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if (warningFor2Hours != null) {
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}
		
		// 当前下午2点停止卖票
		if (messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if (warningFor14Hours != null) {
				messages.add(warningFor14Hours);
			}
		}
		if (messages.isEmpty()) {
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				@SuppressWarnings("unused")
				boolean success = pro.success();
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					String format = MessageFormat.format(payWayPage, orderid.toString());
					return format;//redirect:/f/pay/payWay?orderid=11000777
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		request.getSession().setAttribute("mes", messages);
		model.addAttribute("messages", messages);
		return "/modules/base/indexAirRent";
	}

	@RequestMapping("checkPassword")
	public void checkPassword(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String password1 = request.getParameter("password1");
		String password2 = request.getParameter("password2");
		if(password1==null||password2==null){
			response.getWriter().println("0");//密码不一致
			return;
		}
		if (!password1.equals(password2) || StringUtils.isEmpty(password1) || StringUtils.isEmpty(password2)) {
			response.getWriter().println("0");//密码不一致
			return;
		}
		String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
		if (!password1.matches(regex)||!password2.matches(regex)) {
			response.getWriter().println("1");   //不符合规范（6-16位数字和字母的组合）
			return;
		}else{
			response.getWriter().println("2");   
		}
	}
	@RequestMapping("applycargosave")
	public String applycargosave(TApplycargo tApplycargo, Model model, 
			RedirectAttributes redirectAttributes,HttpServletResponse response,HttpServletRequest request) throws IOException {

		List<String> messages = Lists.newArrayList();
		try{
			BeanValidators.validateWithException(validator, tApplycargo);
		}catch(ConstraintViolationException ex){
			List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
			messages.addAll(list);
		}
		String contactstel = tApplycargo.getContactstel();
		String email = tApplycargo.getEmail();
		if(!ValidateTool.isMobile(contactstel) &&
				!ValidateTool.isPhone(contactstel)) {
			messages.add("联系电话填写不正确");
		}
		if(!ValidateTool.isEmail(email)) {
			messages.add("联系邮箱填写不正确");
		}
		if(messages.isEmpty()) {
			tApplycargo.setAuditstatus(TApplycargo.AUDITSTATUS_NEW);
			tApplycargoService.save(tApplycargo);
			addMessage(redirectAttributes, "申请客运公司车辆加盟成功");
			response.sendRedirect(request.getContextPath()+"/webInfo.jsp");
			return null;
		} else {
			addMessage(model, messages.toArray(new String[]{}));
			response.sendRedirect(request.getContextPath()+"/webInfo.jsp");
			return null;
		}
	}
	@RequestMapping("ipLocation")
	public void ipLocation(HttpServletResponse response,HttpServletRequest request) throws IOException {
		String ip = request.getRemoteAddr();//获取ip
		String backUrl = "";
		if (ip.contains("0:0:0:0:0:0:0:1")||ip.contains("127.0.0.1")) {//本地
			backUrl = "https://api.map.baidu.com/location/ip?ak=pWa6dfvGtqEGvu1L2Mc2WGG1qBSlB8h9"
					+ "&coor=bd09ll";
		}else{
			backUrl = "https://api.map.baidu.com/location/ip?ak=pWa6dfvGtqEGvu1L2Mc2WGG1qBSlB8h9"
					+ "&coor=bd09ll&ip="+ip;
		}
        String result = AuthUtil.doGetString(backUrl);
        JSONObject jsonObject =  JSONObject.fromObject(result);  
        String string;
		try {
			string = jsonObject.getString("content");
		} catch (Exception e) {//定位失败
			e.printStackTrace();
			response.getWriter().println("常州市");
			return;
		}
        if (string!=null) {
        	JSONObject fromObject = jsonObject.fromObject(string);
        	String string2 = fromObject.getString("address_detail");
        	JSONObject fromObject2 = JSONObject.fromObject(string2);
        	String cityname = fromObject2.getString("city");
        	if (StringUtils.isNotEmpty(cityname)) {
        		response.getWriter().println(cityname);   
        	}else{
        		response.getWriter().println("常州市");//根据ip为查询到结果   
        	}
		}else{
			response.getWriter().println("常州市");//根据ip为查询到结果   
		}
	}
}






































